<template>
	<view class="contenter">

		<!-- <view class="text-area">
			<view>
				<button size="default" @click="getLocation" type="default" hover-class="is-hover">gps</button>
			</view>
			<view>
				<button size="default" @click="getLocationGcj02" type="default" hover-class="is-hover">gcj02</button>
			</view>
		</view> -->

		<view id="mapContener" class="map_Contener">

			<button type="primary" v-if="total>curentMarkLen" :loading="moreLoading" @click="loadMore">加载更多</button>
		</view>
	</view>
</template>

<script setup>
	import {
		onMounted,
		onUnmounted,
		ref
	} from "vue";
	import AMapLoader from "@amap/amap-jsapi-loader";

	import {
		getBadDistributionMap,
		getCodeImg
	} from '@/Api/performingLoan.js'


	let map = null;

	var curentLongitude = ref(0)
	var curentLatitude = ref(0)
	var queryParams = ref({
		pageNum: 1,
		pageSize: 30
	})
	var total = ref(0)
	var curentMarkLen = ref(0)
	var moreLoading = ref(false)

	const loadMore = () => {



		if (moreLoading.value == false) {
			moreLoading.value = true
			// alert("加载更多") //加载完成后，过一秒在改成false
			uni.showLoading({
				title: '加载中...'
			});
			queryParams.value.pageNum += 1;

			getPerformingLoanData()
		}


	}

	//获取当前位置经纬度
	const getCurentPosition = (AMap) => {
		// alert("开始获取位置")
		AMap.plugin('AMap.Geolocation', () => {
			var geolocation = new AMap.Geolocation({
				enableHighAccuracy: true, //是否使用高精度定位，默认:true
				timeout: 10000, //超过10秒后停止定位，默认：5s
				position: 'RB', //定位按钮的停靠位置
				offset: [10, 20], //定位按钮与设置的停靠位置的偏移量，默认：[10, 20]
				zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点

			});
			// this.map.addControl(geolocation);
			geolocation.getCurrentPosition((status, result) => {
				if (status == 'complete') {
					// alert("获取成功")

					var startLonLat = JSON.parse(JSON.stringify(result.position))
					curentLongitude.value = startLonLat[0]
					curentLatitude.value = startLonLat[1]

					// alert(curentLongitude.value)
					// alert(curentLatitude.value)
					initMap(AMap);
					//标记当前位置
					markCurrentLocation(AMap)

				} else {
					// alert("获取失败")
					initMap(AMap);
				}
			});
		});
	}


	//初始化地图
	function intMapLoad() {
		uni.showLoading({
			title: '加载中...'
		});
		// alert("初始化地图")
		//alert(curentLongitude.value, curentLatitude.value)
		window._AMapSecurityConfig = {
			securityJsCode: "e14d1ed9ab6db8a2678f31bb4a44badc",
		};
		// alert("1")
		AMapLoader.load({
				key: "e07471cf8b0c49bfdd92fe37f0b38094", // 申请好的Web端开发者Key，首次调用 load 时必填
				version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
				plugins: ["AMap.Scale"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
			})
			.then((AMap) => {
				// alert("2")
				getCurentPosition(AMap)

			})
			.catch((e) => {
				// alert("3")
				alert(e);
			});
	}

	//初始化地图
	const initMap = (AMap) => {
		map = new AMap.Map("mapContener", {
			// 设置地图容器id
			viewMode: "3D", // 是否为3D地图模式
			zoom: 13, // 初始化地图级别
			// center: [116.397428, 39.90923], // 初始化地图中心点位置
			//center: [curentLongitude.value, curentLatitude.value]
			center: [114.515737, 38.048128]
		});
		getPerformingLoanData()
	}

	//获取不良数据
	var timer = null;
	const getPerformingLoanData = async () => {
		var res = await getBadDistributionMap(queryParams.value)
		var rows = res.rows
		curentMarkLen.value = curentMarkLen.value + rows.length
		total.value = res.total
		const markerList = []
		rows.forEach(function(item, index) {
			if (item.currentAddressLonLat != null && item.currentAddressLonLat.length >= 2) {
				const marker = new AMap.Marker({
					position: item.currentAddressLonLat, //经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
					// icon: "/static/map/currentMark.png",
					icon: "/static/map/redFlag.png",
					// size: new AMap.Size(25, 34), //图标尺寸
					title: item.customerName,
					extData: {

						id: item.id
					}
				});

				marker.on("click", function(e) {
					// alert("你点击了Marker=" + e.target._originOpts.extData.id);
					// console.log(e.target._originOpts.extData.id)

					uni.navigateTo({
						url: '/pages/performingLoan/detail?flg=0&id=' + e.target
							._originOpts.extData.id
					});

					// uni.navigateTo({
					// 	url: '/pages/performingLoan/test1'
					// });
				});
				//将创建的点标记添加到已有的地图实例：
				markerList.push(marker)

			}
		})
		if (markerList.length > 0) {
			map.add(markerList);
		}

		timer = setTimeout(() => {
			moreLoading.value = false
			if (timer) {
				clearTimeout(timer);
				timer = null;
			}
		}, 1000);

		uni.hideLoading()
	}

	//标注当前位置
	const markCurrentLocation = (AMap) => {
		// alert("当前位置" + curentLongitude.value + "," + curentLatitude.value)
		const marker = new AMap.Marker({
			position: [curentLongitude.value, curentLatitude.value], //经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
			// icon: "/static/map/currentMark.png",
			icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png",
			// size: new AMap.Size(25, 34), //图标尺寸
			title: "当前位置",
		});

		//将创建的点标记添加到已有的地图实例：
		map.add(marker);


		var text = new AMap.Text({
			text: "当前位置", //标记显示的文本内容
			anchor: "top-center", //设置文本标记锚点位置
			offset: new AMap.Pixel(0, 0),
			// draggable: true, //是否可拖拽
			// cursor: "pointer", //指定鼠标悬停时的鼠标样式。
			// angle: 10, //点标记的旋转角度
			style: {
				//设置文本样式，Object 同 css 样式表
				"padding": ".5rem .75rem",
				// "margin-bottom": "1rem",
				"border-radius": ".25rem",
				"background-color": "red",
				// "width": "15rem",
				"border-width": 0,
				"box-shadow": "0 2px 6px 0 rgba(114, 124, 245, .5)",
				"text-align": "center",
				"font-size": "12px",
				"color": "white",
			},
			position: [curentLongitude.value, curentLatitude.value] //点标记在地图上显示的位置
		});
		//text.setMap(map); //将文本标记设置到地图上
	}

	onMounted(() => {
		intMapLoad()
		//getCodeImg()
		// getPerformingLoanData()
		// uni.getLocation({
		// 	// type: 'gcj02',
		// 	success: function(res) {
		// 		curentLongitude.value = res.longitude
		// 		curentLatitude.value = res.latitude
		// 		alert(curentLongitude.value)
		// 		alert(curentLatitude.value)
		// 		//alert([curentLatitude.value, curentLatitude.value])
		// 		intMap()

		// 	}
		// });



	});

	onUnmounted(() => {
		map?.destroy();
	});
</script>

<style scoped lang="scss">
	page,
	.contenter,
	.map_Contener {
		width: 100%;
		height: 100%;
	}

	.map_Contener {
		position: relative;

		button {
			position: absolute;
			right: 20rpx;
			bottom: 10rpx;
			z-index: 99;
			font-size: 28rpx;
		}
	}
</style>